package de.teamgamma.cansat.groundstation.export;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import de.teamgamma.cansat.groundstation.livestream.TransmittedValue;

/**
 * Exporter for the CSV-Export
 * @author Marc Huisinga
 *
 */
public class CsvExporter implements Exporter {

	@Override
	public void export(ExportableData input, File output) {
		File outputFile = new File(output.getAbsolutePath() + ".csv");
		boolean mkFileSucceeded = false;
		try {
			mkFileSucceeded = outputFile.createNewFile();
		} catch (IOException e1) {
			System.err.println("Invalid output file path!");
		}
		if (mkFileSucceeded) {
			TransmittedValue primaryValue = input.getValues()[0];
			TransmittedValue[] values = new TransmittedValue[input.getValues().length-1];
			int valueIndex = 0;
			for (TransmittedValue currentValue : input.getValues()) {
				if (valueIndex != 0) {
					values[valueIndex-1] = currentValue;
				}
				valueIndex ++;
			}
			try {
				BufferedWriter currentWriter = new BufferedWriter(new FileWriter(outputFile));
				currentWriter.write(primaryValue.getKey() + "(" + primaryValue.getUnit() + "),");
				for (TransmittedValue currentValue : values) {
					currentWriter.write(currentValue.getKey() + "(" + currentValue.getUnit() + ")");
					if (currentValue != values[values.length-1]) {
						currentWriter.write(",");
					}
				}
				currentWriter.write(System.getProperty("line.separator"));
				for (int lineIndex = 0; lineIndex < input.getDataOfKey(primaryValue.getKey()).length; lineIndex ++) {
					currentWriter.write(new Date(Long.valueOf(input.getDate(primaryValue.getKey(), lineIndex))).toString() + ",");
					for (TransmittedValue currentValue : values) {
						currentWriter.write(input.getDate(currentValue.getKey(), lineIndex));
						if (currentValue != values[values.length-1]) {
							currentWriter.write(",");
						}
					}
					currentWriter.write(System.getProperty("line.separator"));
				}
				currentWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
